import sys
import os
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QLabel, QLineEdit, QPushButton, QTextEdit, QFileDialog
)
from PyQt6.QtCore import Qt
from findword_utils import find_word_in_files, play_video_from_timestamp

class FindWordApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle('视频字幕搜索工具')
        self.setGeometry(100, 100, 800, 600)
        
        # 主布局
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        self.layout = QVBoxLayout()
        main_widget.setLayout(self.layout)
        
        # 搜索词输入
        search_layout = QHBoxLayout()
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText('输入要搜索的单词...')
        search_layout.addWidget(self.search_input)
        
        # 目录选择
        self.dir_button = QPushButton('选择目录')
        self.dir_button.clicked.connect(self.select_directory)
        search_layout.addWidget(self.dir_button)
        
        # 搜索按钮
        self.search_button = QPushButton('搜索')
        self.search_button.clicked.connect(self.start_search)
        search_layout.addWidget(self.search_button)
        
        self.layout.addLayout(search_layout)
        
        # 结果按钮容器
        self.result_buttons_container = QWidget()
        self.result_buttons_layout = QVBoxLayout()
        self.result_buttons_container.setLayout(self.result_buttons_layout)
        self.layout.addWidget(self.result_buttons_container)
        
        # 状态栏
        self.status_bar = self.statusBar()
        
        # 初始化变量
        self.selected_dir = "r:\\外文视频"
        
    def select_directory(self):
        """选择搜索目录"""
        dir_path = QFileDialog.getExistingDirectory(self, '选择搜索目录')
        if dir_path:
            self.selected_dir = dir_path
            self.status_bar.showMessage(f'已选择目录: {dir_path}')
            
    def start_search(self):
        """开始搜索"""
        if not self.selected_dir:
            self.status_bar.showMessage('请先选择搜索目录')
            return
            
        search_word = self.search_input.text().strip()
        if not search_word:
            self.status_bar.showMessage('请输入搜索词')
            return
            
        # 清空之前的按钮
        for i in reversed(range(self.result_buttons_layout.count())): 
            self.result_buttons_layout.itemAt(i).widget().setParent(None)
            
        self.status_bar.showMessage('正在搜索...')
        
        try:
            results = find_word_in_files(search_word, self.selected_dir)
            if results:
                self.status_bar.showMessage(f'搜索完成，找到 {len(results)} 个结果')
                
                # 为每个结果创建播放按钮
                for i, result in enumerate(results, 1):
                    btn = QPushButton(f"播放 {i}: {result['file']} ({result['timestamp_s']}-{result['timestamp_e']})")
                    btn.setToolTip(result['line'])  # 鼠标悬停显示完整台词
                    
                    # 使用lambda捕获当前result
                    btn.clicked.connect(lambda _, r=result: (
                        print(f"准备播放: {r['file']}"),
                        play_video_from_timestamp(
                            os.path.normpath(os.path.join(self.selected_dir, r['file'])),
                            r
                        )
                    ))
                    
                    self.result_buttons_layout.addWidget(btn)
            else:
                self.status_bar.showMessage('搜索完成，未找到结果')
        except Exception as e:
            self.status_bar.showMessage(f'搜索出错: {str(e)}')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = FindWordApp()
    window.show()
    sys.exit(app.exec())
